package com.xiaoyu.awakening.user.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaoyu.awakening.user.dao.UserDao;
import com.xiaoyu.awakening.user.entity.UserEntity;
import com.xiaoyu.awakening.user.entity.UserRoleRefEntity;
import com.xiaoyu.awakening.user.dto.RoleDto;
import com.xiaoyu.awakening.user.dto.UserDto;
import com.xiaoyu.awakening.user.dto.req.CreateUserReq;
import com.xiaoyu.awakening.user.enums.UserStatusEnums;
import com.xiaoyu.awakening.user.service.IUserRoleRefService;
import com.xiaoyu.awakening.user.service.IUserService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.util.List;

/**
 * @author wangxiaoyu
 * @since v1.0
 */
@Service
@AllArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserDao, UserEntity> implements IUserService {
    private final IUserRoleRefService userRoleRefService;

    @Override
    public UserEntity getUserByUserName(String username) {
        return super.baseMapper.getUserByUserName(username);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveUser(CreateUserReq createUserReq) {
        UserEntity userEntity = new UserEntity();
        BeanUtil.copyProperties(createUserReq, userEntity);
        //填充默认数据
        userEntity.setStatus(UserStatusEnums.USER_UN_ACTIVE.getStatus());
        userEntity.setCreateTime(LocalDate.now());
        save(userEntity);

        //处理角色信息
        if (CollectionUtil.isEmpty(createUserReq.getRoleList())) {
            //todo：角色默认处理
        }
        List<UserRoleRefEntity> userRoleRefList = createUserReq.getRoleList().stream().map(RoleDto::getId).distinct()
                .map(role -> {
                    UserRoleRefEntity userRoleRefEntity = new UserRoleRefEntity();
                    userRoleRefEntity.setUserId(createUserReq.getId());
                    userRoleRefEntity.setRoleId(role);
                    return userRoleRefEntity;
                }).toList();
        userRoleRefService.saveBatch(userRoleRefList);
        return true;
    }

    @Override
    public boolean logicDeleteUserById(Long id) {
        UserEntity user = getById(id);
        user.setUpdateTime(LocalDate.now());
        user.setStatus(UserStatusEnums.LOGIN_DELETED.getStatus());
        updateById(user);
        return true;
    }

    @Override
    public UserDto details(Long id) {

        return null;
    }
}
